"""日志系统初始化脚本
在应用启动时调用，设置全局日志配置
"""

import os
import sys
from pathlib import Path
from config.log_settings import setup_logging_config
from utils.log_manager import LoggerFactory, get_system_logger

def init_logging_system():
    """初始化日志系统"""
    try:
        # 设置基础配置
        setup_logging_config()
        
        # 创建日志目录
        log_dir = Path('./logs')
        log_dir.mkdir(exist_ok=True)
        
        # 获取系统日志记录器
        system_logger = get_system_logger('logging_init')
        system_logger.info("日志系统初始化成功", log_dir=str(log_dir))
        
        return True
        
    except Exception as e:
        print(f"❌ 日志系统初始化失败: {e}")
        return False

def cleanup_old_logs(days: int = 30):
    """清理旧日志文件"""
    import time
    from datetime import datetime, timedelta
    
    log_dir = Path('./logs')
    if not log_dir.exists():
        return
    
    cutoff_time = time.time() - (days * 24 * 60 * 60)
    cleaned_count = 0
    
    for log_file in log_dir.glob('*.log.*'):
        if log_file.stat().st_mtime < cutoff_time:
            try:
                log_file.unlink()
                cleaned_count += 1
            except Exception as e:
                print(f"清理日志文件失败 {log_file}: {e}")
    
    if cleaned_count > 0:
        system_logger = get_system_logger('log_cleanup')
        system_logger.info(f"清理了 {cleaned_count} 个旧日志文件")

if __name__ == "__main__":
    init_logging_system()